﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYTakeOffFittingConnect : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException("commandData", "is null");
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				IList<Pipe> list = new List<Pipe>();
				IList<XYZ> list2 = new List<XYZ>();
				ISelectionFilter selectionFilter = new PipeSelectionFilter();
				HYPipeConnect hypipeConnect = new HYPipeConnect();
				string text = "侧连接";
				for (;;)
				{
					transaction = new Transaction(document, text);
					transaction.Start();
					list.Clear();
					list2.Clear();
					RevitVersionFuncs.ClearSelection(selection);
					Reference reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, selectionFilter, "选择第一个水管");
					list.Add(document.GetElement(reference) as Pipe);
					list2.Add(reference.GlobalPoint);
					reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, selectionFilter, "选择第二个水管，与第一个水管垂直");
					list.Add(document.GetElement(reference) as Pipe);
					list2.Add(reference.GlobalPoint);
					if (hypipeConnect.NewTakeOffFitting(list, list2) == null)
					{
						MessageBox.Show("连接失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					}
					else
					{
						document.Regenerate();
					}
					transaction.Commit();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
